﻿using Autofac;
using Ewell.BizComponent.Service.IServer;
using Ewell.BizComponent.Service.Model.Constant;
using Ewell.BizComponent.Service.Model.Dto;
using Ewell.BizComponent.Service.Model.Insur.Request;
using Ewell.BizComponent.Service.Model.Insur.Response;
using Ewell.BizComponent.Service.Model.InterProxy;
using Ewell.BizComponent.Service.Model.Invoice.Request;
using Ewell.BizComponent.Service.Model.Request;
using Ewell.BizComponent.Service.Model.Response;
using Ewell.BizComponent.Service.Server;
using Ewell.BizComponent.UI.Charge.Model.Response;
using Ewell.BizComponent.UI.Core.Model;
using Ewell.BizComponent.UI.Core.VievModel;
using Ewell.BizComponent.UI.SearchItemCom.ViewModel;
using Ewell.BizComponent.UI.SearchPersonCom.ViewModel;
using Ewell.Interface.Common.Model.Common;
using Ewell.Interface.Common.Model.GateWay.Dto.Dict;
using Ewell.Interface.Common.Model.GateWay.GateWayUriInfo;
using Ewell.Interface.Common.Utils;
using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Ewell.BizComponent.UI.Charge.ViewModel
{
    public class SettlementVm : ViewModelBase
    {
        /// <summary>
        /// 患者信息
        /// </summary>
        private PatientVm _patient;
        public PatientVm patient
        {
            get => _patient; set
            {
                if (value != _patient)
                {
                    _patient = value;
                    OnPropertyChanged(nameof(patient));
                }
            }
        }
        /// <summary>
        /// 已选择的医保费别
        /// </summary>
        private PatientTypeVm _selectedPatientType;
        public PatientTypeVm selectedPatientType
        {
            get
            {
                return _selectedPatientType;
            }
            set
            {
                if (_selectedPatientType != value)
                {
                    _selectedPatientType = value;
                    OnPropertyChanged(nameof(selectedPatientType));
                }
            }
        }
        /// <summary>
        /// 收费信息
        /// </summary>
        private ChargingInfoVm _chargingInfo;
        public ChargingInfoVm chargingInfo
        {
            get => _chargingInfo; set
            {
                if (_chargingInfo != value)
                {
                    _chargingInfo = value;
                    OnPropertyChanged(nameof(chargingInfo));
                }
            }
        }
        /// <summary>
        /// 检索组件主类
        /// </summary>
        private SearchPersonComVm _searchPersonComVm;
        public SearchPersonComVm searchPersonComVm
        {
            get => _searchPersonComVm;
            set
            {
                if (value != _searchPersonComVm)
                {
                    _searchPersonComVm = value;
                    OnPropertyChanged(nameof(searchPersonComVm));
                }
            }
        }
        /// <summary>
        /// 检索组件显示
        /// </summary>
        private Visibility _searchPersonViewVisib = Visibility.Collapsed;
        public Visibility searchPersonViewVisib
        {
            get => _searchPersonViewVisib;
            set
            {
                if (value != _searchPersonViewVisib)
                {
                    _searchPersonViewVisib = value;
                    OnPropertyChanged(nameof(searchPersonViewVisib));
                }
            }
        }
        /// <summary>
        /// 选择项主类
        /// </summary>
        private SearchItemComVm _searchItemComVm;
        public SearchItemComVm searchItemComVm
        {
            get => _searchItemComVm;
            set
            {
                if (_searchItemComVm != value)
                {
                    _searchItemComVm = value;
                    OnPropertyChanged(nameof(searchItemComVm));
                }
            }
        }
        /// <summary>
        /// 选择项组件显示
        /// </summary>
        private Visibility _searchItemViewVisib = Visibility.Collapsed;
        public Visibility searchItemViewVisib
        {
            get => _searchItemViewVisib;
            set
            {
                if (value != _searchItemViewVisib)
                {
                    _searchItemViewVisib = value;
                    OnPropertyChanged(nameof(searchItemViewVisib));
                }
            }
        }
        /// <summary>
        /// 支付主类
        /// </summary>
        public CashierVm cashierVm { get; set; }
        /// <summary>
        /// 支付组件是否显示
        /// </summary>
        private Visibility _cashierViewVisib = Visibility.Collapsed;
        public Visibility cashierViewVisib
        {
            get => _cashierViewVisib;
            set
            {
                if (value != _cashierViewVisib)
                {
                    _cashierViewVisib = value;
                    OnPropertyChanged(nameof(cashierViewVisib));
                }
            }
        }
        /// <summary>
        /// 继续按钮是否可用
        /// </summary>
        private bool _settBtnCanUsed = true;
        public bool settBtnCanUsed
        {
            get => _settBtnCanUsed;
            set
            {
                if (_settBtnCanUsed != value)
                {
                    _settBtnCanUsed = value;
                    OnPropertyChanged(nameof(settBtnCanUsed));
                }
            }
        }
        /// <summary>
        /// 医保结算结果
        /// </summary>
        public OutPayResponse outPayResponse { get; set; }
        /// <summary>
        /// 收费结果
        /// </summary>
        public OutChargeResponse outChargeResponse { get; set; }

        public bool InsurFlag => selectedPatientType.no != "1";

        public IOutSettlementServer outSettlementServer { get; set; } = Global.Container.Resolve<IOutSettlementServer>();
        public IInsurServer insurServer { get; set; } = Global.Container.Resolve<IInsurServer>();
        public IDialogCoordinator dialogCoordinator { get; set; } = DialogCoordinator.Instance;
        public IInvoiceServer invoiceServer { get; set; }=Global.Container.Resolve<IInvoiceServer>();

        public SettlementVm()
        {
            this.searchPersonComVm = new SearchPersonComVm();
            this.searchItemComVm = new SearchItemComVm();
        }



        /// <summary>
        /// 结算
        /// </summary>
        public ICommand Settlement => new RelayCommand(async (object param) =>
        {
            LogHelper.Debug($"Settlement {JsonConvert.SerializeObject(param)}");
            searchItemViewVisib = Visibility.Collapsed;
            searchPersonViewVisib = Visibility.Collapsed;
            if (InsurFlag && outPayResponse == null)//医保
            {
                #region 医保读卡显示
                LogHelper.Debug($"Settlement 【医保读卡begin】");
                if (!await InsurReadCardAsync()) return;
                LogHelper.Debug($"Settlement 【医保读卡end】");
                #endregion

                #region 选择项显示
                LogHelper.Debug($"Settlement 【医保选择项begin】");
                if (!InsurSearchItem()) return;
                LogHelper.Debug($"Settlement 【医保选择项end】");
                #endregion

                #region 医保结算
                LogHelper.Debug($"Settlement 【医保结算begin】");
                if (!await InsurSetlAsync()) return;
                if (outPayResponse == null)
                    return;
                LogHelper.Debug($"Settlement 【医保结算end】");
                #endregion
            }
            if (cashierViewVisib != Visibility.Visible)
            {
                cashierViewVisib = Visibility.Visible;
                return;
            }
            //支付
            this.cashierVm.paySetl.Execute(param);
            var onlinePayList = cashierVm.payWayList.Where(x => x.interfaceId.HasValue && x.amount > 0 && x.paySuccess != true)?.ToList();
            if (onlinePayList.Count > 0)
            {
                return;
            }
            //结算
            await SetlAsync();
            //医保结算后
            await InsurSetlFinashAsync();
            //发票
            FormPrint();
        });

        /// <summary>
        /// 取消结算
        /// </summary>
        public ICommand CancelSettlement => new RelayCommand(async (object param) =>
        {
            //退支付
            if (cashierVm.payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true))
            {
                cashierVm.paySetlCancel.Execute(param);
            }
            //退医保
            if (InsurFlag && outPayResponse != null)
                await InsurCancelSetlAsync();
        });
        /// <summary>
        /// HIS结算
        /// </summary>
        private async Task SetlAsync()
        {
            List<PayRecordDto> payRecords = new List<PayRecordDto>();
            foreach (var payWay in cashierVm.payWayList.Where(w => w.amount > 0 && ((w.interfaceId.HasValue && w.paySuccess == true) || !w.interfaceId.HasValue)))
            {
                PayRecordDto payRecordDto = new PayRecordDto()
                {
                    payAmount = payWay.amount,
                    payWayId = payWay.no,
                    thirdPartTranId = payWay.payTxnNo,
                };
                payRecords.Add(payRecordDto);
            }
            if (outPayResponse != null && InsurFlag)
            {
                if (outPayResponse.insurPayRecordList != null)
                {
                    foreach (var item in outPayResponse.insurPayRecordList)
                    {
                        payRecords.Add(new PayRecordDto()
                        {
                            insurPaymentFlag = "1",
                            payAmount = item.payAmt??0,
                            payWayId = item.payWay,
                        });
                    }
                }
            }
            OutSettlementRequest settlementRequest = new OutSettlementRequest()
            {
                settlementInfo = new SettlementDto()
                {
                    outEncounterId = chargingInfo.encounterId.ToString(),
                    settlementId = chargingInfo.settlementId.ToString(),
                    payTypeCoding = chargingInfo.settlementTypeCode,
                    amount = chargingInfo.amount.Value,
                    discountAmount = chargingInfo.discountAmount.Value,
                    insurAmount = chargingInfo.insurAmount ?? 0,
                    selfPayAmount = chargingInfo.recAmount.Value,
                    payRecordList = payRecords,
                }
            };
            try
            {
                OutSettlementResponse response = outSettlementServer.Settlement(settlementRequest);
                this.outChargeResponse = new OutChargeResponse()
                {
                    outEncountId = settlementRequest.settlementInfo.outEncounterId,
                };
            }
            catch (SpeedException ex)
            {
                await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"结算失败!{ex.Message}");
                //退支付
                if (cashierVm.payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true))
                {
                    cashierVm.paySetlCancel.Execute(this);
                }
                //退医保
                if (InsurFlag && outPayResponse != null)
                    await InsurCancelSetlAsync();
                return;
            }
            catch (Exception ex)
            {
                await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"结算失败!{ex.Message}");
                //退医保
                if (InsurFlag && outPayResponse != null)
                    await InsurCancelSetlAsync();
                //退支付
                if (cashierVm.payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true))
                {
                    cashierVm.paySetlCancel.Execute(this);
                }
                return;
            }
        }
        /// <summary>
        /// 医保结算
        /// </summary>
        private async Task<bool> InsurSetlAsync()
        {
            if (this.outPayResponse == null)
            {
                List<DataSelectRequest> alreadySelectDataList = new List<DataSelectRequest>();
                if (searchItemComVm.dataSelectItemList != null && searchItemComVm.dataSelectItemList.Count > 0)
                {
                    foreach (var dataSelect in this.searchItemComVm.dataSelectItemList)
                    {
                        if (dataSelect.mustFlag != "1") continue;
                        if (dataSelect.componentTypeCoding == "1")
                            alreadySelectDataList.Add(dataSelect.selectedBasicData.CopyProperties<DataSelectRequest>());
                        else if (dataSelect.componentTypeCoding == "2")
                        {
                            alreadySelectDataList.Add(new DataSelectRequest()
                            {
                                basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                                basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                                basicDataId = dataSelect.textBasicData,
                                basicDataName = dataSelect.textBasicData,
                                basicDataNo = dataSelect.textBasicData,
                                basicDataExtInfo = dataSelect.textBasicData,
                            });
                        }
                        else if (dataSelect.componentTypeCoding == "3")
                        {
                            alreadySelectDataList.Add(new DataSelectRequest()
                            {
                                basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                                basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                                basicDataId = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                                basicDataName = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                                basicDataNo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                                basicDataExtInfo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                            });
                        }
                        else if (dataSelect.componentTypeCoding == "4")
                        {
                            alreadySelectDataList.Add(new DataSelectRequest()
                            {
                                basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                                basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                                basicDataId = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                                basicDataName = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                                basicDataNo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                                basicDataExtInfo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                            });
                        }
                    }
                }
                RequestHeader requestHeader = new RequestHeader()
                {
                    interfaceId = long.Parse(selectedPatientType.interfaceId),
                    alreadySelectDataList = alreadySelectDataList,
                    cardInfo = searchPersonComVm.readCardResponse,
                };
                try
                {
                    if (this.chargingInfo.settlementTypeCode == "1")
                    {
                        OutRegisterResponse outRegisterResponse = insurServer.beforeOutRegister(requestHeader, new OutRegisterBeforeRequest()
                        {
                            outPayMtNo = this.chargingInfo.settlementId.ToString(),
                            patientId = this.patient.patientId,
                            visitNo = this.chargingInfo.encounterId.ToString(),
                        });
                        this.outPayResponse = outRegisterResponse.CopyProperties<OutPayResponse>();
                    }
                    else if (this.chargingInfo.settlementTypeCode == "2")
                    {
                        this.outPayResponse = insurServer.beforeOutPay(requestHeader, new OutPayBeforeRequest()
                        {
                            outPayMtNo = this.chargingInfo.settlementId.ToString(),
                            patientId = this.patient.patientId,
                            visitNo = this.chargingInfo.encounterId.ToString(),
                        });
                    }
                }
                catch (SpeedException ex)
                {
                    await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"医保预算失败!{ex.Message}");
                    return false;
                }
                catch (Exception ex)
                {
                    await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"医保预算失败!{ex.Message}");
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 医保结算后
        /// </summary>
        private async Task InsurSetlFinashAsync()
        {
            if (this.outPayResponse == null)
                return;
            List<DataSelectRequest> alreadySelectDataList = new List<DataSelectRequest>();
            if (searchItemComVm.dataSelectItemList != null && searchItemComVm.dataSelectItemList.Count > 0)
            {
                foreach (var dataSelect in this.searchItemComVm.dataSelectItemList)
                {
                    if (dataSelect.mustFlag != "1") continue;
                    if (dataSelect.componentTypeCoding == "1")
                        alreadySelectDataList.Add(dataSelect.selectedBasicData.CopyProperties<DataSelectRequest>());
                    else if (dataSelect.componentTypeCoding == "2")
                    {
                        alreadySelectDataList.Add(new DataSelectRequest()
                        {
                            basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                            basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                            basicDataId = dataSelect.textBasicData,
                            basicDataName = dataSelect.textBasicData,
                            basicDataNo = dataSelect.textBasicData,
                            basicDataExtInfo = dataSelect.textBasicData,
                        });
                    }
                    else if (dataSelect.componentTypeCoding == "3")
                    {
                        alreadySelectDataList.Add(new DataSelectRequest()
                        {
                            basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                            basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                            basicDataId = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                            basicDataName = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                            basicDataNo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                            basicDataExtInfo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                        });
                    }
                    else if (dataSelect.componentTypeCoding == "4")
                    {
                        alreadySelectDataList.Add(new DataSelectRequest()
                        {
                            basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                            basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                            basicDataId = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                            basicDataName = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                            basicDataNo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                            basicDataExtInfo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                        });
                    }
                }
            }
            RequestHeader requestHeader = new RequestHeader()
            {
                interfaceId = long.Parse(selectedPatientType.interfaceId),
                alreadySelectDataList = alreadySelectDataList,
                cardInfo = searchPersonComVm.readCardResponse,
            };
            try
            {
                if (this.chargingInfo.settlementTypeCode == "1")
                {
                    insurServer.afterOutRegister(requestHeader, new OutRegisterAfterRequest()
                    {
                        outPayMtNo = this.chargingInfo.settlementId.ToString(),
                        patientId = this.patient.patientId,
                        visitNo = this.chargingInfo.encounterId.ToString(),
                    });
                }
                else if (this.chargingInfo.settlementTypeCode == "2")
                {
                    insurServer.afterOutPay(requestHeader, new OutPayAfterRequest()
                    {
                        outPayMtNo = this.chargingInfo.settlementId.ToString(),
                        patientId = this.patient.patientId,
                        visitNo = this.chargingInfo.encounterId.ToString(),
                    });
                }
            }
            catch (SpeedException ex)
            {
                await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"结算成功！医保结算后处理异常!{ex.Message}");
            }
            catch (Exception ex)
            {
                await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"结算成功！医保结算后处理异常!{ex.Message}");
            }
        }
        /// <summary>
        /// 撤销医保结算
        /// </summary>
        private async Task InsurCancelSetlAsync()
        {
            if (this.outPayResponse != null)
            {
                List<DataSelectRequest> alreadySelectDataList = new List<DataSelectRequest>();
                if (searchItemComVm.dataSelectItemList != null && searchItemComVm.dataSelectItemList.Count > 0)
                {
                    foreach (var dataSelect in this.searchItemComVm.dataSelectItemList)
                    {
                        if (dataSelect.mustFlag != "1") continue;
                        if (dataSelect.componentTypeCoding == "1")
                            alreadySelectDataList.Add(dataSelect.selectedBasicData.CopyProperties<DataSelectRequest>());
                        else if (dataSelect.componentTypeCoding == "2")
                        {
                            alreadySelectDataList.Add(new DataSelectRequest()
                            {
                                basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                                basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                                basicDataId = dataSelect.textBasicData,
                                basicDataName = dataSelect.textBasicData,
                                basicDataNo = dataSelect.textBasicData,
                                basicDataExtInfo = dataSelect.textBasicData,
                            });
                        }
                        else if (dataSelect.componentTypeCoding == "3")
                        {
                            alreadySelectDataList.Add(new DataSelectRequest()
                            {
                                basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                                basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                                basicDataId = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                                basicDataName = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                                basicDataNo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                                basicDataExtInfo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd"),
                            });
                        }
                        else if (dataSelect.componentTypeCoding == "4")
                        {
                            alreadySelectDataList.Add(new DataSelectRequest()
                            {
                                basicDataDictTypeId = dataSelect.basicDataDictTypeId,
                                basicDataDictTypeNo = dataSelect.basicDataDictTypeNo,
                                basicDataId = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                                basicDataName = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                                basicDataNo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                                basicDataExtInfo = dataSelect.timeBasicData?.ToString("yyyy-MM-dd HH:mm:ss"),
                            });
                        }
                    }
                }
                RequestHeader requestHeader = new RequestHeader()
                {
                    interfaceId = long.Parse(selectedPatientType.interfaceId),
                    alreadySelectDataList = alreadySelectDataList,
                    cardInfo = searchPersonComVm.readCardResponse,
                };
                try
                {
                    if (this.chargingInfo.settlementTypeCode == "1")
                    {
                        insurServer.cancelOutRegisterPreview(requestHeader, new OutRegisterCancelPreviewRequest() { outPayMtNo = this.chargingInfo.settlementId.ToString(), patientId = this.patient.patientId, visitNo = this.chargingInfo.encounterId.ToString() });
                    }
                    else if (this.chargingInfo.settlementTypeCode == "2")
                    {
                        insurServer.cancelOutPayPreview(requestHeader, new OutPayCancelPreviewRequest() { outPayMtNo = this.chargingInfo.settlementId.ToString(), patientId = this.patient.patientId, visitNo = this.chargingInfo.encounterId.ToString() });
                    }
                    this.outPayResponse = null;
                }
                catch (SpeedException ex)
                {
                    await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"取消医保结算失败!可能存在单边账!{ex.Message}");
                    this.outPayResponse = null;
                    return;
                }
                catch (Exception ex)
                {
                    await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"取消医保结算失败!可能存在单边账!{ex.Message}");
                    this.outPayResponse = null;
                    return;
                }
            }
        }

        /// <summary>
        /// 医保读卡
        /// </summary>
        private async Task<bool> InsurReadCardAsync()
        {
            if (searchPersonViewVisib == Visibility.Visible && searchPersonComVm.readCardResponse == null)
            {
                NeedReadCardResponse needReadCardResponse = insurServer.GetNeedReadCard(new RequestHeader() { interfaceId = long.Parse(selectedPatientType.interfaceId) }, new NeedReadCardRequest()
                {
                    currentBizTransactionCoding = chargingInfo.settlementTypeCode == "1" ? InsurBusinessCoding.HIS挂号正算前.code : InsurBusinessCoding.HIS收费正算前.code,
                    patientId = patient.patientId,
                    payMtNo = chargingInfo.settlementId.ToString(),
                    visitNo = chargingInfo.encounterId.ToString(),
                });
                //需要读卡
                if (needReadCardResponse.needReadCardStatus is "1" or "2")
                {
                    searchPersonViewVisib = Visibility.Visible;
                    if (needReadCardResponse.needReadCardStatus == "1")
                    {
                        await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"接口设置必须读卡！请读卡后继续！");
                        return false;
                    }
                    return true;
                }
            }
            if (searchPersonComVm.readCardResponse == null&& searchPersonViewVisib != Visibility.Visible)
            {
                if (string.IsNullOrWhiteSpace(selectedPatientType.interfaceId) || selectedPatientType.interfaceId.Trim() == "0")
                {
                    await this.dialogCoordinator.ShowMessageAsync(this, "警告", $"结算的医保类型信息有误！请联系管理员排查绑定的接口信息!");
                    return false;
                }
                NeedReadCardResponse needReadCardResponse = insurServer.GetNeedReadCard(new RequestHeader() { interfaceId = long.Parse(selectedPatientType.interfaceId) }, new NeedReadCardRequest()
                {
                    currentBizTransactionCoding = chargingInfo.settlementTypeCode == "1" ? InsurBusinessCoding.HIS挂号正算前.code : InsurBusinessCoding.HIS收费正算前.code,
                    patientId = patient.patientId,
                    payMtNo = chargingInfo.settlementId.ToString(),
                    visitNo = chargingInfo.encounterId.ToString(),
                });
                //需要读卡
                if (needReadCardResponse.needReadCardStatus is "1" or "2")
                {
                    searchPersonViewVisib = Visibility.Visible;
                    if (needReadCardResponse.needReadCardStatus == "2")
                        settBtnCanUsed = false;
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 医保选择项
        /// </summary>
        private bool InsurSearchItem()
        {
            if (searchItemViewVisib != Visibility.Visible)
            {
                this.searchItemComVm.currentBizParams = this.chargingInfo.settlementTypeCode == "1" ? JsonConvert.SerializeObject(new OutRegisterBeforeRequest()
                {
                    outPayMtNo = this.chargingInfo.settlementId.ToString(),
                    patientId = this.patient.patientId,
                    visitNo = chargingInfo.encounterId.ToString(),
                }) : JsonConvert.SerializeObject(new OutPayPreviewRequest()
                {
                    outPayMtNo = this.chargingInfo.settlementId.ToString(),
                    patientId = this.patient.patientId,
                    visitNo = chargingInfo.encounterId.ToString(),
                });
                List<DataSelectItemResponse> dataSelectItemResponses = insurServer.InitDataSelectItem(new RequestHeader()
                {
                    cardInfo = searchPersonComVm.readCardResponse,
                    interfaceId = long.Parse(selectedPatientType.interfaceId),
                }, new DataSelectItemInitRequest()
                {
                    currentBizParams = this.searchItemComVm.currentBizParams,
                    currentBizTransactionCoding = this.chargingInfo.settlementTypeCode == "1" ? InsurBusinessCoding.HIS挂号正算前.code : InsurBusinessCoding.HIS收费正算前.code,
                });
                if (dataSelectItemResponses != null && dataSelectItemResponses.Count > 0)
                {
                    var datalist = new List<DataSelectItemVm>();
                    foreach (var item in dataSelectItemResponses)
                    {
                        var dataSelectItemVm = item.CopyProperties<DataSelectItemVm>();
                        if (item.componentTypeCoding == "1" && !string.IsNullOrWhiteSpace(item.basicDataNo))
                        {
                            dataSelectItemVm.basicDataList = new List<BasicDataVm>();
                            var basicDatas = insurServer.SearchDataSelectItem(new RequestHeader() { interfaceId = long.Parse(searchItemComVm.selectedPatientType.interfaceId), cardInfo = this.searchItemComVm.readCardResponse, alreadySelectDataList = new List<DataSelectRequest>() }, new DataSelectItemQueryRequest() { basicDataDictTypeId = long.Parse(item.basicDataDictTypeId), basicDataDictTypeNo = item.basicDataDictTypeNo, currentBizParams = this.searchItemComVm.currentBizParams, currentBizTransactionCoding = this.searchItemComVm.outPreSettlementRequest.settlementTypeCode == "1" ? "101" : "201", keyword = string.Empty });
                            if (dataSelectItemVm != null)
                            {
                                dataSelectItemVm.basicDataList = new List<BasicDataVm>();
                                if (basicDatas != null && basicDatas.Count() > 0)
                                {
                                    foreach (var basicData in basicDatas)
                                    {
                                        dataSelectItemVm.basicDataList.Add(new BasicDataVm()
                                        {
                                            basicDataDictTypeId = dataSelectItemVm.basicDataDictTypeId,
                                            basicDataDictTypeNo = dataSelectItemVm.basicDataDictTypeNo,
                                            basicDataId = basicData.basicDataId,
                                            basicDataNo = basicData.basicDataNo,
                                            basicDataName = basicData.basicDataName,
                                            basicDataExtInfo = basicData.basicDataExtInfo,
                                            pinyin = basicData.pinyin,
                                            wubi = basicData.wubi,
                                        });
                                    }
                                }
                            }
                            dataSelectItemVm.selectedBasicData = dataSelectItemVm.basicDataList.FirstOrDefault(f => f.basicDataNo == item.basicDataNo);
                        }
                        if (item.componentTypeCoding == "2" && !string.IsNullOrWhiteSpace(item.basicDataNo))
                        {
                            dataSelectItemVm.textBasicData = item.basicDataId;
                        }
                        if (item.componentTypeCoding == "3" && !string.IsNullOrWhiteSpace(item.basicDataId))
                        {
                            try
                            {
                                dataSelectItemVm.timeBasicData = DateTime.Parse(item.basicDataId);
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (item.componentTypeCoding == "4" && !string.IsNullOrWhiteSpace(item.basicDataId))
                        {
                            try
                            {
                                dataSelectItemVm.timeBasicData = DateTime.Parse(item.basicDataId);
                            }
                            catch (Exception)
                            {
                            }
                        }
                        //dataSelect.componentTypeCoding == "1"
                        datalist.Add(dataSelectItemVm);
                    }
                    this.searchItemComVm.dataSelectItemList = datalist;
                    searchItemViewVisib = Visibility.Visible;
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 单据打印
        /// </summary>
        private async void FormPrint()
        {
            if (this.outChargeResponse == null) return;
            List<string> formCodes = new List<string>();
            if (this.chargingInfo.settlementTypeCode == "1")
                formCodes.Add(FormCoding.R_O_009_E.code);
            else
                formCodes.Add(FormCoding.R_O_008_E.code);
            QueryFormInfoReq req = new QueryFormInfoReq()
            {
                formCodes=formCodes
            };
            FormPrintManagementDubboService formPrintManagementDubboService = new FormPrintManagementDubboService();
            var gateWayResult = formPrintManagementDubboService.queryFormInfoByFormCodes.Post<List<FormPrintResp>>(req).CheckState();

            if (gateWayResult.@object == null || gateWayResult.@object.Count == 0)
            {
                LogHelper.Debug("没有需要打印的单据!跳过打印");
                return;
            }
            var formPrintResp = gateWayResult.@object.FirstOrDefault();

            if (!formPrintResp.interfaceId.HasValue || formPrintResp.interfaceId == 0)
            {
                LogHelper.Debug("没有需要打印的单据!跳过打印");
                return;
            }

            if ("1".Equals(formPrintResp.formPrintRuleCoding))//通用设置
            {
                //询问开具
                if (formPrintResp.formPrintRuleXGeneral.formPrintCategoryCoding is 6)
                {
                    MessageDialogResult messageDialogResult= await this.dialogCoordinator.ShowMessageAsync(this, "询问?", $"是否开具发票");
                    if (messageDialogResult != MessageDialogResult.Affirmative)
                    {
                        return;
                    }
                }
            }
            else if ("2".Equals(formPrintResp.formPrintRuleCoding))//按菜单设置
            {
                if (formPrintResp.formPrintRuleXMenuList == null || formPrintResp.formPrintRuleXMenuList.Count == 0)
                    return;
                var formPrintRuleXMenu = formPrintResp.formPrintRuleXMenuList.FirstOrDefault(f => f.menuID ==LoginInfo.menuId);
                if (formPrintRuleXMenu == null) return;
                if (formPrintRuleXMenu.formPrintCategoryCoding is 6)
                {
                    var messageBoxResult = MessageBox.Show("是否开具发票", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.ServiceNotification);
                    if (messageBoxResult != MessageBoxResult.Yes)
                        return;
                }
            }
            if (!formPrintResp.interfaceId.HasValue || formPrintResp.interfaceId == 0)
                return;
            //开具发票
            CurrentInvoiceRequest currentInvoiceRequest = new CurrentInvoiceRequest()
            {
                invoiceUsageCoding = this.chargingInfo.settlementTypeCode
            };
            var currentInvoiceResponses = invoiceServer.QueryCurrentInvoice(formPrintResp.interfaceId.Value, currentInvoiceRequest);

            //var currentInvoiceResponse = currentInvoiceResponses.FirstOrDefault(f => f.invoiceTypeCoding == "2");
            //if (currentInvoiceResponse == null) return;
            //InvoiceIssueRequest invoiceIssueRequest = new InvoiceIssueRequest()
            //{
            //    invoiceAllotId = currentInvoiceResponse.invoiceAllotId,
            //    invoiceUsageCoding = currentInvoiceRequest.invoiceUsageCoding,
            //    repairPrintFlag = "0",
            //    invoiceList = new List<InvoicingIndexRequest>()
            //    {
            //        new InvoicingIndexRequest()
            //        {
            //            invoiceIndex="1",
            //            invoiceAmt=this.chargingInfo.recAmount,
            //            hisBizIds=new List<string>{ this.chargingInfo.settlementId.ToString() },
            //        }
            //    }
            //};
            //invoiceServer.IssueInvoice(formPrintResp.interfaceId.Value, invoiceIssueRequest);
        }
    }
}
